# Create your views here.

from django.http import HttpResponseRedirect, Http404, HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib import auth
from django.contrib.auth.decorators import login_required

from provider.models import File
from fluffyprovider import settings
import security

from fluffyprovider.settings import CENTRAL_REGISTER, PROVIDER_ADDRESS ,PROVIDER_NAME, MEDIA_ROOT
import urllib2
import datetime
import base64
import mimetypes

try:
    import simplejson as json
except ImportError:
    import json

REGISTER_API = "http://" + CENTRAL_REGISTER + "/api"

@login_required()
def register(request):
    opener = urllib2.build_opener()
    urllib2.install_opener(opener)
    url = "%s/%s/" % (REGISTER_API, 'sp_list')
    
    name = PROVIDER_NAME
    address = PROVIDER_ADDRESS
    datadict = {'name': name, 'address':address}
    data = json.dumps(datadict)
    print url
    apirequest = urllib2.Request(url, data=data)
    apirequest.add_header('Content-Type', 'application/json')
    apirequest.get_method = lambda: 'PUT'
    result = opener.open(apirequest).read()
    # result izgleda ovako:
    #{
    #"status": "EXISTS",        ## ili "OK"
    #"name": "provider1", 
    #"address": "127.0.0.1:8001"
    #}
    #
    resultobjs = json.loads(result)
    get_cert()
    return render_to_response('register.html',
                             {'status': resultobjs['status'],'name':resultobjs['name']})

def get_cert():
    opener = urllib2.build_opener()
    urllib2.install_opener(opener)
    url = "%s/%s/" % (REGISTER_API, 'make_cert')
    
    name = PROVIDER_NAME
    address = PROVIDER_ADDRESS
    datadict = {'name': name, 'address':address}
    data = json.dumps(datadict)
    apirequest = urllib2.Request(url, data=data)
    apirequest.add_header('Content-Type', 'application/json')
    apirequest.get_method = lambda: 'PUT'
    result = opener.open(apirequest).read()
    resultobjs = json.loads(result)
    if resultobjs['status'] == "OK":
        keys = security.loadKeys(resultobjs['keys'])
        settings.myKeys = keys
    
@login_required()
def send_file_list(request):
    opener = urllib2.build_opener()
    urllib2.install_opener(opener)
    url = "%s/%s/" % (REGISTER_API, 'file_list')
    filelist = []
    files = File.objects.all()
    for f in files:
        filelist.append({'name': f.path,
                         'author': f.author,
                         'description': f.description})
    datadict = {'service-provider': PROVIDER_NAME, 'file-list': filelist}
    data = json.dumps(datadict)
    print url
    apirequest = urllib2.Request(url, data=data)
    apirequest.add_header('Content-Type', 'application/json')
    apirequest.get_method = lambda: 'PUT'
    result = opener.open(apirequest).read()
    resultobjs = json.loads(result)
    # rezultat izgleda ovako:
    #{
    #"file-list": [
    #    {
    #        "status": "EXISTS", 
    #        "sp": "provider1", 
    #        "name": "/home/stef/nesto.txt"
    #    }, 
    #    {
    #        "status": "EXISTS", 
    #        "sp": "provider1", 
    #        "name": "/home/stef/nesto2.txt"
    #    }
    #]
    #}

    return render_to_response('send_file_list.html',
                             {"file_list":resultobjs["file-list"]})

@login_required()
def get_file_list(request):
    opener = urllib2.build_opener()
    urllib2.install_opener(opener)
    url = "%s/%s/" % (REGISTER_API, 'file_list')
    json_src = urllib2.urlopen(url).read()
    file_list = json.loads(json_src)["file-list"]

    print file_list
    # json_src, tj. file_list izgleda ovako
    #{
    #"file-list": [
    #    {
    #        "author": "nesto", 
    #        "sp": "provider1", 
    #        "sp-address": "127.0.0.1:8001", 
    #        "description": "Neka bolesna knjiga", 
    #        "name": "/home/stef/nesto.txt"
    #    }, 
    #    {
    #        "author": "nesto 2", 
    #        "sp": "provider1", 
    #        "sp-address": "127.0.0.1:8001", 
    #        "description": "Ova je jos bolja", 
    #        "name": "/home/stef/nesto2.txt"
    #    }
    #]
    #}
    local = []
    remote = []
    for file in file_list:
        if file['sp'] == PROVIDER_NAME:
            local.append(file)
        else:
            file['address']=file['sp-address']
            remote.append(file)
    return render_to_response('file_list.html',
                             {'local':local,'remote':remote})


def get_remote_file(request, address, filename):
    opener = urllib2.build_opener()
    urllib2.install_opener(opener)
    url = "http://" + address + "/api/get_file/" # url apija od drugog sp-a
    
    datadict = {'service-provider': PROVIDER_NAME,
                'username': request.user.username,
                'filename': filename}
                
    data = json.dumps(datadict)
    apirequest = urllib2.Request(url, data=data)
    apirequest.add_header('Content-Type', 'application/json')
    apirequest.get_method = lambda: 'PUT'
    print url
    json_src = opener.open(apirequest).read()
    result = json.loads(json_src)
    if result["status"] == "NOT FOUND":
        return Http404
    filecontent = base64.b64decode(result["data"]) #dekodiraj podatke
    mimetype = mimetypes.guess_type(filename)[0] #odredi mimetype (uzimamo index 0 jer je 1 encoding)
    return HttpResponse(content = filecontent, mimetype = mimetype) #salji fajl s ispravnim mimetypeom

def index(request):
    name = "Guest"
    user = request.user
    if not user.is_anonymous() :
        name = user.username
    return render_to_response('index.html', {}, context_instance=RequestContext(request))


def login(request):
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    user = auth.authenticate(username=username, password=password)
    if user is not None and user.is_active:
        # Correct password, and the user is marked "active"
        auth.login(request, user)
        # Redirect to a success page.
        print "welcome"
        return render_to_response('index.html', {}, context_instance=RequestContext(request))
    else:
        # Show an erroro page
        return render_to_response("index.html",{"error":"error"}, context_instance=RequestContext(request))

def logout(request):
    auth.logout(request)
    return HttpResponseRedirect("/")
